{% extends 'base.html' %}
{% load static %}

{% block title %}战斗 - {{ battle.id }}{% endblock %}

{% block extra_head %}
<!-- 引入BattleBridge -->
<script src="{% static 'js/battleBridge.js' %}"></script>
{% endblock %}

{% block content %}
<div class="container-fluid mt-3">
    <div class="row">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5>战斗 #{{ battle.id }}</h5>
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="debug-mode">
                        <label class="form-check-label" for="debug-mode">调试模式</label>
                    </div>
                </div>
                <div class="card-body">
                    <div class="battle-info mb-3">
                        <div class="row">
                            <div class="col-md-6">
                                <strong>玩家1:</strong> {{ battle.player1.username }}
                            </div>
                            <div class="col-md-6">
                                <strong>玩家2:</strong> {{ battle.player2.username }}
                            </div>
                        </div>
                        <div class="row mt-2">
                            <div class="col-md-6">
                                <strong>创建时间:</strong> {{ battle.created_at|date:"Y-m-d H:i:s" }}
                            </div>
                            <div class="col-md-6">
                                <strong>状态:</strong> {{ battle.get_status_display }}
                            </div>
                        </div>
                    </div>

                    <div class="battle-controls mb-3">
                        <button id="btn-start-battle" class="btn btn-success" disabled>开始</button>
                        <button id="btn-pause-battle" class="btn btn-warning" disabled>暂停</button>
                        <button id="btn-reset-battle" class="btn btn-danger">重置</button>
                    </div>

                    <div class="battle-frame">
                        <iframe id="battle-iframe"
                                src="/static/battle/index.html"
                                width="100%"
                                height="500px"
                                frameborder="0"
                                title="战斗游戏界面"
                                sandbox="allow-scripts allow-same-origin allow-forms allow-modals allow-popups"
                                allow="script-src 'unsafe-eval' 'unsafe-inline'"></iframe>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card mb-3">
                <div class="card-header">
                    <h5>JSON调试输入</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="json-input" class="form-label">输入JSON命令:</label>
                        <textarea id="json-input" class="form-control" rows="8" placeholder='{
  "player": "a",
  "type": "move",
  "self": {
    "type": "unit",
    "id": 1
  },
  "target": {
    "type": "position",
    "id": 0,
    "position": {
      "x": 5,
      "y": 5
    }
  }
}'></textarea>
                    </div>
                    <button id="btn-send-json" class="btn btn-primary btn-sm">发送JSON命令</button>
                    <button id="btn-format-json" class="btn btn-outline-secondary btn-sm">格式化JSON</button>
                </div>
            </div>

            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5>战斗日志</h5>
                    <button id="btn-clear-log" class="btn btn-sm btn-outline-secondary">清空</button>
                </div>
                <div class="card-body">
                    <div id="battle-log" class="battle-log"></div>
                </div>
            </div>
        </div>
    </div>
</div>

{% csrf_token %}

<style>
    .battle-log {
        height: 500px;
        overflow-y: auto;
        font-family: monospace;
        font-size: 0.9rem;
        background-color: #f8f9fa;
        padding: 10px;
        border-radius: 4px;
    }

    .log-entry {
        margin-bottom: 5px;
        word-wrap: break-word;
    }

    .log-command {
        color: #007bff;
    }

    .log-result {
        color: #28a745;
    }

    .log-error {
        color: #dc3545;
    }

    .log-system {
        color: #6c757d;
    }
</style>

<script>
    // 添加日志函数
    function addLog(message, type = 'info') {
        const logContainer = document.getElementById('battle-log');
        const logEntry = document.createElement('div');
        logEntry.className = 'log-entry';

        // 根据类型设置样式
        if (type === 'command') {
            logEntry.classList.add('log-command');
        } else if (type === 'result' || type === 'success') {
            logEntry.classList.add('log-result');
        } else if (type === 'error' || type === 'warning') {
            logEntry.classList.add('log-error');
        } else if (type === 'system') {
            logEntry.classList.add('log-system');
        }

        // 添加时间戳
        const now = new Date();
        const timestamp = now.toLocaleTimeString();

        logEntry.innerHTML = `<span class="text-muted">[${timestamp}]</span> ${message}`;
        logContainer.appendChild(logEntry);

        // 滚动到底部
        logContainer.scrollTop = logContainer.scrollHeight;
    }

    // 发送消息到iframe
    function sendToIframe(data) {
        const iframe = document.getElementById('battle-iframe');
        if (iframe && iframe.contentWindow) {
            // console.log('发送消息到iframe:', data);
            iframe.contentWindow.postMessage(data, '*');
        } else {
            console.error('无法发送消息，iframe不可用');
            addLog('无法发送消息，iframe不可用', 'error');
        }
    }

    // 生成命令ID
    function generateCommandId() {
        return Date.now() + '-' + Math.floor(Math.random() * 1000);
    }

    // 获取CSRF Token
    function getCSRFToken() {
        return document.querySelector('input[name="csrfmiddlewaretoken"]').value;
    }

    // 调试模式变量
    let isDebugMode = false;

    // 初始化BattleBridge
    const battleBridge = new BattleBridge();

    // 扩展battleBridge以支持战斗页面特有功能
    battleBridge.initBattlePage = function() {
        console.log('初始化战斗页面桥接');

        const iframe = document.getElementById('battle-iframe');
        this.init(iframe, addLog);

        // 监听调试模式切换
        document.getElementById('debug-mode').addEventListener('change', (e) => {
            isDebugMode = e.target.checked;
            this.setDebugMode(isDebugMode);
            addLog('调试模式: ' + (isDebugMode ? '开启' : '关闭'), 'info');
        });

        // 监听按钮点击
        document.getElementById('btn-start-battle').addEventListener('click', this.startBattle.bind(this));
        document.getElementById('btn-pause-battle').addEventListener('click', this.pauseBattle.bind(this));
        document.getElementById('btn-reset-battle').addEventListener('click', this.resetBattle.bind(this));
        document.getElementById('btn-clear-log').addEventListener('click', this.clearLog.bind(this));

        // 监听JSON调试按钮
        document.getElementById('btn-send-json').addEventListener('click', this.sendJsonCommand.bind(this));
        document.getElementById('btn-format-json').addEventListener('click', this.formatJson.bind(this));
    };

    // 扩展battleBridge的命令处理方法
    battleBridge.handleCommandFromIframe = function(command) {
        console.log('处理来自iframe的命令:', command);
        addLog(`收到命令: ${command.type} (玩家: ${command.player})`, 'command');

        // 这里可以添加命令验证逻辑
        // 目前直接记录到日志

        // 如果不是调试模式，需要进行命令验证
        if (!this.debugMode) {
            this.validateAndSendCommand(command);
        }
    };

        // 发送JSON命令到iframe
        sendJsonCommand: function() {
            const jsonInput = document.getElementById('json-input');
            const jsonText = jsonInput.value.trim();

            if (!jsonText) {
                addLog('请输入JSON命令', 'error');
                return;
            }

            try {
                const command = JSON.parse(jsonText);

                // 验证CommandModel格式
                if (!command.player || !command.type) {
                    addLog('JSON格式错误: 缺少必需字段 player 或 type', 'error');
                    return;
                }

                console.log('发送JSON命令:', command);
                addLog('发送JSON命令: ' + JSON.stringify(command), 'command');

                // 根据调试模式决定发送方式
                if (isDebugMode) {
                    // 调试模式：直接发送给当前iframe，使用统一的CommandModel格式
                    console.log('调试模式: 直接发送给当前iframe');
                    addLog('调试模式: 直接发送给当前iframe', 'info');

                    // 统一消息格式：直接发送CommandModel
                    const message = {
                        data: command
                    };
                    sendToIframe(message);
                } else {
                    // 非调试模式：发送给服务器，让服务器广播给所有同场战斗的页面
                    console.log('非调试模式: 发送给服务器广播');
                    addLog('非调试模式: 发送给服务器广播', 'info');

                    // 统一消息格式：直接发送CommandModel
                    handlePlayerCommand(command);
                }

            } catch (e) {
                addLog('JSON解析错误: ' + e.message, 'error');
            }
        },

        // 格式化JSON
        formatJson: function() {
            const jsonInput = document.getElementById('json-input');
            const jsonText = jsonInput.value.trim();

            if (!jsonText) {
                return;
            }

            try {
                const parsed = JSON.parse(jsonText);
                const formatted = JSON.stringify(parsed, null, 2);
                jsonInput.value = formatted;
                addLog('JSON已格式化', 'info');
            } catch (e) {
                addLog('JSON格式化失败: ' + e.message, 'error');
            }
        },

        // 添加命令回调
        addCommandCallback: function(commandId, callback) {
            this.commandCallbacks[commandId] = callback;
        },

        // 开始战斗
        startBattle: function() {
            console.log('开始战斗');
            addLog('开始战斗', 'system');
            document.getElementById('btn-start-battle').disabled = true;
            document.getElementById('btn-pause-battle').disabled = false;

            // 发送符合CommandModel格式的初始化命令
            const initCommand = {
                player: "a",
                type: "init",
                self: {
                    type: "player",
                    id: 1
                },
                param: {
                    map: 1,
                    players: [
                        {
                            player: "a",
                            color: "#000000",
                            startPosition: { x: 0, y: 0 }
                        },
                        {
                            player: "b",
                            color: "#ffffff",
                            startPosition: { x: 10, y: 10 }
                        }
                    ],
                    me: "a"
                }
            };

            console.log('发送初始化命令:', initCommand);
            addLog('发送初始化命令: ' + JSON.stringify(initCommand), 'system');
            sendToIframe(initCommand);
        },

        // 暂停战斗
        pauseBattle: function() {
            console.log('暂停战斗');
            addLog('暂停战斗', 'system');
            document.getElementById('btn-start-battle').disabled = false;
            document.getElementById('btn-pause-battle').disabled = true;

            sendToIframe({
                type: 'battleState',
                state: 'paused'
            });
        },

        // 重置战斗
        resetBattle: function() {
            console.log('重置战斗');
            addLog('重置战斗', 'system');
            document.getElementById('btn-start-battle').disabled = false;
            document.getElementById('btn-pause-battle').disabled = true;

            sendToIframe({
                type: 'resetBattle'
            });
        },

        // 清空日志
        clearLog: function() {
            const logContainer = document.getElementById('battle-log');
            logContainer.innerHTML = '';
            addLog('日志已清空', 'info');
        },

        // 获取CSRF Token
        getCsrfToken: function() {
            return document.querySelector('input[name="csrfmiddlewaretoken"]').value;
        }
    };

    // WebSocket连接
    let battleSocket = null;
    let isWebSocketConnected = false;

    // 初始化WebSocket连接
    function initWebSocket() {
        const battleId = {{ battle.id|default:"null" }};
        const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const wsUrl = `${wsProtocol}//${window.location.host}/ws/battles/${battleId}/`;

        battleSocket = new WebSocket(wsUrl);

        battleSocket.onopen = function(e) {
            console.log('WebSocket连接已建立');
            isWebSocketConnected = true;
            addLog('WebSocket连接已建立', 'system');
        };

        battleSocket.onmessage = function(e) {
            const data = JSON.parse(e.data);
            console.log('WebSocket收到消息:', data);

            // 处理不同类型的消息
            if (data.type === 'command') {
                // 收到其他玩家的命令，转发给iframe
                const command = data.command;
                // 统一消息格式：直接发送CommandModel
                const message = {
                    data: command
                };
                sendToIframe(message);
                console.log('收到的命令详情:', command);
                addLog(`收到玩家 ${data.username} 的命令: ${command.commandType || command.type}`, 'command');
            } else if (data.type === 'chat') {
                // 处理聊天消息
                addLog(`${data.username}: ${data.message}`, 'chat');
            } else if (data.type === 'connection_established') {
                // 连接建立消息
                addLog(`${data.message}`, 'system');
            } else if (data.type === 'battle_update') {
                // 处理战斗更新消息
                const message = data.message;
                if (message.type === 'practice_battle_error') {
                    // 处理练习赛错误
                    handlePracticeBattleError(message);
                } else {
                    // 其他战斗更新消息
                    console.log('战斗更新:', message);
                    addLog(`战斗更新: ${message.type}`, 'system');
                }
            } else if (data.type === 'error') {
                // 错误消息
                addLog(`错误: ${data.message}`, 'error');
            }
        };

        battleSocket.onclose = function(e) {
            console.log('WebSocket连接已关闭');
            isWebSocketConnected = false;
            addLog('WebSocket连接已关闭', 'error');

            // 尝试重新连接
            setTimeout(function() {
                if (!isWebSocketConnected) {
                    addLog('尝试重新连接WebSocket...', 'system');
                    initWebSocket();
                }
            }, 3000);
        };

        battleSocket.onerror = function(e) {
            console.error('WebSocket错误:', e);
            addLog('WebSocket连接错误', 'error');
        };
    }

    // 发送命令到WebSocket
    function sendCommandToWebSocket(command) {
        if (battleSocket && battleSocket.readyState === WebSocket.OPEN) {
            const message = {
                type: 'command',
                command: command,  // 直接发送CommandModel
                user_id: {{ user.id }},
                username: '{{ user.username }}'
            };
            battleSocket.send(JSON.stringify(message));
            console.log('WebSocket发送消息:', message);
            return true;
        } else {
            console.error('WebSocket未连接，无法发送命令');
            addLog('WebSocket未连接，无法发送命令', 'error');
            return false;
        }
    }

    // 处理练习赛错误
    function handlePracticeBattleError(errorData) {
        console.error('练习赛错误:', errorData);

        // 显示错误信息
        const errorMessage = errorData.error_message || '未知错误';
        const failedPlayer = errorData.failed_player || '未知玩家';
        const failedRound = errorData.failed_round || 0;
        const stopReason = errorData.stop_reason || 'unknown';

        // 添加错误日志
        addLog('=== 练习赛错误 ===', 'error');
        addLog(`错误原因: ${errorMessage}`, 'error');
        addLog(`失败玩家: ${failedPlayer}`, 'error');
        addLog(`失败回合: ${failedRound}`, 'error');
        addLog(`停止原因: ${stopReason}`, 'error');
        addLog('练习赛已停止，请检查代码并修复错误', 'error');

        // 显示模态框或弹窗
        if (typeof showPracticeErrorModal === 'function') {
            showPracticeErrorModal(errorData);
        } else {
            // 如果没有模态框函数，使用alert
            alert(`练习赛错误\n\n错误信息: ${errorMessage}\n失败玩家: ${failedPlayer}\n失败回合: ${failedRound}\n\n请检查代码并修复错误后重新开始练习赛。`);
        }

        // 停止当前的战斗逻辑（如果有的话）
        if (typeof stopBattleExecution === 'function') {
            stopBattleExecution();
        }
    }

    // 修改handlePlayerCommand函数，使用WebSocket发送命令
    function handlePlayerCommand(command) {
        // 生成命令ID
        const commandId = generateCommandId();
        command.commandId = commandId;
        command.battleId = {{ battle.id|default:"null" }};

        // 在调试模式下，直接通过验证并发送回iframe
        if (isDebugMode) {
            console.log('调试模式: 直接通过验证命令', command);

            // 统一消息格式：直接发送CommandModel
            const message = {
                data: command
            };
            sendToIframe(message);
            return;
        }

        // 使用WebSocket发送命令
        if (isWebSocketConnected) {
            if (sendCommandToWebSocket(command)) {
                console.log('通过WebSocket发送命令:', command);
                addLog(`发送命令: ${command.type}`, 'command');

                // 添加命令回调
                battleBridge.addCommandCallback(commandId, function(result) {
                    console.log('命令结果:', result);
                });
            }
        } else {
            // 如果WebSocket未连接，回退到HTTP请求
            console.log('WebSocket未连接，使用HTTP请求发送命令');
            addLog('WebSocket未连接，使用HTTP请求发送命令', 'warning');

            // 添加命令回调
            battleBridge.addCommandCallback(commandId, function(result) {
                console.log('命令结果:', result);
            });

            // 发送命令到服务器进行验证
            fetch('/battles/api/command/validate/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCSRFToken()
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                console.log('命令验证结果:', result);

                if (result.valid) {
                    // 验证通过，发送命令到iframe
                    data.valid = true;
                    sendToIframe(data);
                } else {
                    // 验证失败，记录错误
                    console.error('命令验证失败:', result.reason);
                    addLog(`命令验证失败: ${result.reason}`, 'error');
                }
            })
            .catch(error => {
                console.error('命令验证请求失败:', error);
                addLog(`命令验证请求失败: ${error.message}`, 'error');
            });
        }
    }

    // 在页面加载完成后初始化WebSocket和battleBridge
    document.addEventListener('DOMContentLoaded', function() {
        // 监听来自iframe的postMessage事件
        window.addEventListener('message', function(event) {
            if (battleBridge) {
                battleBridge.handleIframeMessage(event);
            }
        });

        // 将battleBridge暴露给全局window
        window.battleBridge = battleBridge;

        // 初始化战斗页面特有功能
        battleBridge.initBattlePage();

        // 初始化WebSocket连接
        initWebSocket();

        // 在页面卸载前发送ping请求，保持连接
        window.addEventListener('beforeunload', function() {
            fetch('/battles/api/battle/ping/{{ battle.id|default:"null" }}/', {
                method: 'GET',
                headers: {
                    'X-CSRFToken': getCSRFToken()
                }
            });
        });
    });
</script>
{% endblock %}